package com.ruoyi.common.imgconflate;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.core.io.ClassPathResource;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

public class PosterQrcodeUtil {

    public static void main(String[] args) {
//		GraphicsEnvironment ge=GraphicsEnvironment.getLocalGraphicsEnvironment();
//        String[] fa=ge.getAvailableFontFamilyNames();
//        for (String s:fa) {
//            System.out.println(s);
//        }
        String qrCodePath = "D:\\img\\gh_82c77f85fadd_860.jpg";
        String outPutPath = "D:\\img\\abcd.jpg";
        String backgroundPath = "D:\\img\\poster_default_01.jpg";

        Map map = new HashMap();
        map.put("NICKNAME","大月饼");
        map.put("HEADIMG","https://sjd.hxtcsx.com/infra/file/1747439750615781378/get//yjj/complain/63dcc0313258dee3bc72705a05090aecad328478fd66510f20c1a064d78a4b39.jpg");
        overlapImageUrl(qrCodePath,outPutPath,map);

    }

    public static String overlapImageUrl(String backgroundPath,String outPutPath, Map params) {
        try {
            //设置背景主图
            BufferedImage background = setSizeImage(300,500, ImageIO.read(new File(Const.whiteBg)));
            Graphics2D g = background.createGraphics();
            //消除文字锯齿
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            //消除锯齿
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            //设置背景
            setImg(g,backgroundPath,0,0,300,500,0);

            Font font = new Font("微软雅黑", Font.BOLD, 36);
            drawStringWithMultiLine(g,font,Color.BLACK,"这里",200,50,50);

            g.dispose();
            ImageIO.write(background, "jpg", new File(outPutPath));
            return outPutPath;
        }catch(Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        }
    }

    public static MultipartFile overlapImage(String qrCode,String backgroundPath,Map params) {
        try {
            //设置背景主图
            URL url = new URL(Const.whiteBg);
            InputStream is = url.openStream();
            BufferedImage background = setSizeImage(300,500, ImageIO.read(is));
            Graphics2D g = background.createGraphics();
            //消除文字锯齿
            g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
            //消除锯齿
            g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            //设置背景
            setImg(g,backgroundPath,0,0,300,500,0);
//            setImg(g,"D:\\img\\poster_default_01.jpg",0,0,300,500,0);

            /**
             * 设置二维码
             */
            HashMap qrcodeObj = JSONUtil.toBean(Convert.toStr(params.get("qrcodeObj")), HashMap.class);
            //方形二维码
//            setImg(g,qrCode,Convert.toInt(qrcodeObj.get("left")),Convert.toInt(qrcodeObj.get("top")),Convert.toInt(qrcodeObj.get("width")),Convert.toInt(qrcodeObj.get("height")),0);
            //圆形二维码
            setImg(g,qrCode,Convert.toInt(qrcodeObj.get("left")),Convert.toInt(qrcodeObj.get("top")),(Convert.toInt(qrcodeObj.get("radius")) * 2),(Convert.toInt(qrcodeObj.get("radius")) * 2),1);

            //设置文本
            if (ObjectUtil.isNotEmpty(Convert.toStr(params.get("textBox"),null))) {
                HashMap textBoxObj = JSONUtil.toBean(Convert.toStr(params.get("textBox")), HashMap.class);
                Font font = new Font("Arial", Font.PLAIN, Convert.toInt(textBoxObj.get("fontSize")));
                drawStringWithMultiLine(g,font,Color.BLACK,Convert.toStr(textBoxObj.get("text")),(Convert.toInt(textBoxObj.get("width")) + 20),Convert.toInt(textBoxObj.get("left")),(Convert.toInt(textBoxObj.get("top")) + 10));
            }

            //设置头像
            if (ObjectUtil.isNotEmpty(Convert.toStr(params.get("headBox"),null))) {
                HashMap headBoxObj = JSONUtil.toBean(Convert.toStr(params.get("headBox")), HashMap.class);
                setImg(g,Convert.toStr(params.get("headBoxValue")),Convert.toInt(headBoxObj.get("left")),Convert.toInt(headBoxObj.get("top")),Convert.toInt(headBoxObj.get("width")),Convert.toInt(headBoxObj.get("height")),1);
//                setImg(g,"D:\\img\\head.jpeg",Convert.toInt(headBoxObj.get("left")),Convert.toInt(headBoxObj.get("top")),Convert.toInt(headBoxObj.get("width")),Convert.toInt(headBoxObj.get("height")),1);
            }

            //设置昵称
            if (ObjectUtil.isNotEmpty(Convert.toStr(params.get("nickBox"),null))) {
                HashMap nickBoxObj = JSONUtil.toBean(Convert.toStr(params.get("nickBox")), HashMap.class);
                Font font = new Font("微软雅黑", Font.BOLD, 14);
                drawStringWithMultiLine(g,font,Color.BLACK,Convert.toStr(params.get("nickBoxValue")),Convert.toInt(nickBoxObj.get("width")),Convert.toInt(nickBoxObj.get("left")),(Convert.toInt(nickBoxObj.get("top")) + 10));
            }
            g.dispose();
            return fileCase(background);
        }catch(Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            return null;
        }
    }

    /**
     * Graphic2D文本绘制换行，多行绘制
     * @param graphics2D  Graphics2D画笔实例
     * @param text        需要绘制的文本内容
     * @param maxWidth    一行的总宽度（像素）
     * @param startX      X坐标起始点（像素）
     * @param startY      Y坐标起始点（像素）
     */
    public static void drawStringWithMultiLine(Graphics2D graphics2D, Font fontSty,Color color, String text, int maxWidth, int startX, int startY) {
        //设置字体样式
        graphics2D.setFont(fontSty);
        graphics2D.setColor(color);
        //获取画笔的字体
        Font font = graphics2D.getFont();
        //通过JLabel获取文本的总长度和总高度
        JLabel jLabel = new JLabel(text);
        jLabel.setFont(font);
        FontMetrics fontMetrics = jLabel.getFontMetrics(font);
        int textLength = text.length();
        //一行的总长度，用于判断是否超出了范围
        int totalWidth = fontMetrics.stringWidth(text);
        //计算一行的高度
        int textHeight = fontMetrics.getHeight();

        if (totalWidth > maxWidth) {
            //总长度超过了整个长度限制
            //已经写了多少行
            int alreadyWriteLine = 0;
            //目前一行写的长度
            int nowWidth = 0;
            for (int i = 0; i < textLength; i++) {
                //获取单个字符的长度
                int oneWordWidth = fontMetrics.charWidth(text.charAt(i));
                //判断目前的一行加上这个字符的长度是否超出了总长度
                int tempWidth = oneWordWidth + nowWidth;
                if (tempWidth > maxWidth) {
                    //如果超出了一行的总长度，则要换成下一行
                    nowWidth = 0;
                    alreadyWriteLine++;
                    int writeY = startY + alreadyWriteLine * textHeight;
                    graphics2D.drawString(text.charAt(i) + "", startX + nowWidth, writeY);
                    nowWidth = oneWordWidth;
                } else {
                    //当前行长度足够，可以直接画
                    int writeY = startY + alreadyWriteLine * textHeight;
                    graphics2D.drawString(text.charAt(i) + "", startX + nowWidth, writeY);
                    nowWidth = tempWidth;
                }
            }
        } else {
            //没有超过限制，直接画
            graphics2D.drawString(text, startX, startY);
        }
    }

    /**
     * 设置图片
     * @param graphics2D
     * @param headImgUrl 图片路径
     * @param positionX X轴坐标
     * @param positionY Y轴坐标
     * @param width 图片宽度
     * @param height 图片高度
     * @param isFillet 是否转成圆角 1：是、0：否
     * @throws IOException
     */
    public static void setImg(Graphics2D graphics2D,String headImgUrl,Integer positionX,Integer positionY,Integer width, Integer height,Integer isFillet) throws IOException {
        URL url = new URL(headImgUrl);
        InputStream is = url.openStream();
        BufferedImage bufferedImage = setSizeImage(width,height,ImageIO.read(is));
        //转为圆角
        if (isFillet == 1) {
            bufferedImage = ChangeImage.makeRoundedCorner(bufferedImage, 180);
        }
        graphics2D.drawImage(bufferedImage, positionX, positionY, bufferedImage.getWidth(), bufferedImage.getHeight(), null);
    }

    /**
     * 设置图片大小的公共方法
     */
    public static BufferedImage setSizeImage(int x,int y,BufferedImage bfi) {
        BufferedImage bufferedImage = new BufferedImage(x,y,BufferedImage.TYPE_INT_RGB);
        bufferedImage.getGraphics().drawImage(
            bfi.getScaledInstance(x, y, Image.SCALE_SMOOTH), 0, 0, null);
        return bufferedImage;
    }

    public static MultipartFile fileCase(BufferedImage image) {
        //得到BufferedImage对象
        MultipartFile multipartFile = null;
        try {
            //创建一个ByteArrayOutputStream
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            //把BufferedImage写入ByteArrayOutputStream
            ImageIO.write(image, "png", os);
            //ByteArrayOutputStream转成InputStream
            InputStream input = new ByteArrayInputStream(os.toByteArray());
            //InputStream转成MultipartFile
            multipartFile = new MockMultipartFile("file", "file.png", "text/plain", input);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return multipartFile;
    }
}
